package com.videoshare.user;

import javax.servlet.http.*;
import org.apache.struts.action.*;
import org.apache.commons.logging.*;
import com.sapientia.user.dao.*;
import com.sapientia.user.*;
import java.util.*;
import java.sql.*;
import javax.sql.*;

public class UserRegistrationAction extends Action {

	/**
	 * @param args
	 */
	
	private static Log log = LogFactory.getLog(UserRegistrationAction.class);
	
	public ActionForward execute(
			ActionMapping mapping,
			ActionForm form,
			HttpServletRequest request,
			HttpServletResponse response) throws Exception
	{
		
		if( isCancelled(request) )
		{
			return mapping.findForward("Welcome");
		}
		
		UserRegistrationForm userForm = (UserRegistrationForm)form;
		
		
		// ---------------put business logic here-----------
		Connection conn = getDataSource(request,"userDB").getConnection();
		UserDAO dao = DAOFactory.createUserDAO(conn);
		int user = 0;
		
		
		// imposta il profilo dell'utente e le date di inizio e scadenza
		// della registrazione in millisecondi dal 1970
		if(userForm.getProfile() == null)
			userForm.setProfile(UserConstants.USER_PROFILE);
		java.util.Date date = new java.util.Date();
		long currentDate = date.getTime();
		String strCurrentDate = Long.toString(currentDate);
		String strEndDate = Long.toString(currentDate + UserConstants.REGISTRATION_VALIDITY_MILLISEC);
		
		userForm.setRegDate(strCurrentDate);
		userForm.setEndDate(strEndDate);
		
		
		try{
			user = dao.insertUser(userForm);
		}
		catch(SQLException sqle)
		{
			sqle.printStackTrace();
		}
		finally{
				conn.close();
		}
		
		//--------------------------------------------------
		
		
		log.trace("In execute(..) method of UserRegistrationAction");
		if( isCancelled(request) )
		{
			log.debug("Cancel button pushed!");
			return mapping.findForward("welcome");
		}
		
		// business logic worked out well 
		if( user == 1 )
		{
			return mapping.findForward("success");
		}
		else
		{
			return mapping.findForward("failure");
		}
	}

}
